//
//  ComposeViewVC.swift
//  weiboSwift1.0
//
//  Created by xuNick on 16/4/25.
//  Copyright © 2016年 NN. All rights reserved.
//

import UIKit

let KtoolHeight:CGFloat = 40

import SVProgressHUD

class ComposeViewVC: UIViewController {
    
 

    
    
    override func viewDidLoad() {
       super.viewDidLoad()
        self.setupUI()
    }
    
    
    //MARK: - 布局
    private func setupUI(){
    
        view.backgroundColor = UIColor.whiteColor()
        
        self.setupNav()
        //添加textview
        self.view.addSubview(textView!)
        self.view.addSubview(tools!)
        self.view.addSubview(pictureView!)
        
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardChageFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        
    }
    
    private func setupNav(){
        
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: UIBarButtonItemStyle.Plain, target: self, action: "dismiss")
        
        navigationItem.titleView = titleView
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightButton)
        navigationItem.rightBarButtonItem?.enabled = false
    }
    
    @objc private func dismiss(){
        self.dismissViewControllerAnimated(true, completion: nil)
    }
  
    @objc private func send(){
      //发送微博
        if pictureView!.hidden {
            update()
        }else{
            upload()
        }

    }
    
    /// 发送图片微博
    private func upload(){
        
        // 请求地址
        let urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
        
        // 请求参数
        let params = [
            "access_token": UserAccountViewModel.shareUserAccountViewModel.accessToken ?? "",
            "status": textView!.text!,
        ]
        let data = UIImagePNGRepresentation(self.pictureView!.imageList!.first!)!
        NetworkingTool.shareWorkTools.upLoad(urlString, params: params, datas: ["pic": data]) { (responseObject, error) -> () in
            if error != nil {
                print("发送失败\(error)")
                SVProgressHUD.showErrorWithStatus("发送失败")
                return
            }
            SVProgressHUD.showSuccessWithStatus("发送成功")
        }
    }

    
    
    
    
    /// 发送文字微博
    private func update(){
        // 发送文字微博
        // 请求地址
        let urlString = "https://api.weibo.com/2/statuses/update.json"
        
        // 请求参数
        let params = [
            "access_token": UserAccountViewModel.shareUserAccountViewModel.accessToken ?? "",
            "status": textView!.text!
        ]
        
        // 发送请求
        NetworkingTool.shareWorkTools.request(RequestMethod.Post, urlString: urlString, parameters: params) { (responseObject, error) -> () in
            
            if error != nil {
                print("发送失败\(error)")
                SVProgressHUD.showErrorWithStatus("发送失败")
                return
            }
            SVProgressHUD.showSuccessWithStatus("发送成功")
        }
    }

    
    //MARK: -  私有功能
    private func selectPicture(){
        let vc = UIImagePickerController()
        vc.delegate = self
      
        self.presentViewController(vc, animated: true, completion: nil)
        
        
        
    }
    private func switchKeyboard(){
        textView?.becomeFirstResponder()
        textView?.inputView = textView?.inputView == nil ? emoticonKeyboard : nil
        textView?.reloadInputViews()
    }
    
    
    //MARK: -  懒加载控件
    private lazy var emoticonKeyboard: EmojiKeyBoardView = {
        let keyboard = EmojiKeyBoardView(frame: CGRect(x: 0, y: 0, width: KscreenWidth, height: 216))
        return keyboard
    }()

    
    
    
    lazy var pictureView:ComposePictureview? = {
        
        let layout = UICollectionViewFlowLayout()
        
       let view = ComposePictureview(frame: CGRect(x: 0, y: 200, width: KscreenWidth, height: KscreenWidth), collectionViewLayout: layout)
        view.selectedPictureClosure = {[weak self] in
            self!.selectPicture()
        }
        return view
    }()
    
    
    
    lazy var textView:TextView? = {
    let view = TextView(frame: self.view.frame)
        view.delegate = self
    view.text = ""
        return view
    }()
        
    private lazy var rightButton: UIButton = {
        let rightButton = UIButton(textColor: UIColor.whiteColor(), fontSize: 14)
        rightButton.addTarget(self, action: "send", forControlEvents: UIControlEvents.TouchUpInside)
        rightButton.setTitle("发送", forState: UIControlState.Normal)
        // 设置不同状态下的背景图
        rightButton.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: UIControlState.Disabled)
        rightButton.setBackgroundImage(UIImage(named: "common_button_orange"), forState: UIControlState.Normal)
        rightButton.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), forState: UIControlState.Highlighted)
        
        // 设置不同状态的文字颜色
        rightButton.setTitleColor(UIColor.grayColor(), forState: UIControlState.Disabled)
        
        rightButton.frame.size = CGSize(width: 45, height: 28)
        
        // 不启用
        // rightButton.enabled = false
        return rightButton
    }()
    private lazy var titleView: UILabel = {
        
        let titleView = UILabel()
        // 指定行数
        titleView.numberOfLines = 0
        // 指定字体的颜色
        titleView.textColor = UIColor.blackColor()
        titleView.font = UIFont.systemFontOfSize(14)
        // 设置文字居中
        titleView.textAlignment = .Center
        if let name = UserAccountViewModel.shareUserAccountViewModel.account?.name {
            let text = "发微博\n\(name)"
            // 求出name所在的字符串范围
            let range = (text as NSString).rangeOfString(name)
            let attrText = NSMutableAttributedString(string: text)
            // 添加属性: 参数1：属性列表（字典类型），参数2：添加的范围
            attrText.addAttributes([NSForegroundColorAttributeName: UIColor.lightGrayColor(), NSFontAttributeName: UIFont.systemFontOfSize(20), NSStrokeWidthAttributeName: 2, NSStrokeColorAttributeName: UIColor.redColor()], range:   range)
            // 添加一个属性的
            // addAttribute(<#T##name: String##String#>, value: <#T##AnyObject#>, range: <#T##NSRange#>)
            // 设置富文本
            titleView.attributedText = attrText
            // titleView.text = text
        }else{
            titleView.text = "发微博"
        }
        titleView.sizeToFit()
        return titleView
    }()
    
    lazy var tools:ComposeToolBar? = {
        let view = ComposeToolBar(frame: CGRect(x: 0, y: KscreenHeight - KtoolHeight, width: KscreenWidth, height: KtoolHeight))
        view.clickButtonClosure = {[weak self] (type: ComposeToolBarButtonType) in
            switch type {
            case .Picture:
                self?.selectPicture()
                break
            case .Mention:
                break
            case .Trend:
                break
            case .Emoticon:
                self?.switchKeyboard()
                break
            case .Add:
                break
            }
        }
        return view
    }()
    
    @objc private func keyboardChageFrame(noti: NSNotification) {
        
        /**
         UIKeyboardWillChangeFrameNotification; userInfo = {
         UIKeyboardAnimationCurveUserInfoKey = 7;
         UIKeyboardAnimationDurationUserInfoKey = "0.25";
         UIKeyboardBoundsUserInfoKey = "NSRect: {{0, 0}, {375, 258}}";
         UIKeyboardCenterBeginUserInfoKey = "NSPoint: {187.5, 796}";
         UIKeyboardCenterEndUserInfoKey = "NSPoint: {187.5, 538}";
         UIKeyboardFrameBeginUserInfoKey = "NSRect: {{0, 667}, {375, 258}}";
         UIKeyboardFrameEndUserInfoKey = "NSRect: {{0, 409}, {375, 258}}";
         UIKeyboardIsLocalUserInfoKey = 1;
         }}
         
         */
        let endFrame = (noti.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        print(endFrame)
        
    
        UIView.animateWithDuration(0.25) { () -> Void in
            self.tools?.frame.origin.y = endFrame.origin.y - KtoolHeight
        }
    }

}

extension ComposeViewVC: UITextViewDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    
    func textViewDidChange(textView: UITextView) {
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        // 关闭当前界面
        let img = image.scaleToWidth(600)
        //        let data = UIImagePNGRepresentation(img)
        //        data?.writeToFile("/Users/teacher/Desktop/\(random()/3).png", atomically: true)
        pictureView!.addImage(img)
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
    
    
    
    
    
    
    
}
